<?php


namespace app\admin\controller\jizhan;

use app\admin\model\HtnsActivity;
use app\admin\model\HtnsActivityProduct;
use app\admin\model\HtnsActivityProductCate;
use app\admin\model\HtnsFdOrder;
use app\admin\model\HtnsFdOrderDay;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsProduct;
use app\admin\traits\Curd;
use app\api\services\ActivityProductService;
use app\common\controller\AdminController;
use app\model\htns\FdOrder;
use app\model\product\product\StoreProduct;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站-品牌联盟-用户返点每日统计")
 */
class ReturnPointOrderDay extends AdminController
{

    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsFdOrderDay();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $uid = input('id');
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['uid']) && $filterArr['uid']) {
                    $whereArr[] = ['uid', '=', $filterArr['uid']];
                }
                if (isset($filterArr['orderId']) && $filterArr['orderId']) {
                    $whereO['order_id'] = $filterArr['orderId'];
                    $order = HtnsOrder::where($whereO)->find();
                    $whereArr[] = ['oid', '=', $order['id']];
                }
                if (isset($filterArr['grade3Phone'])  && $filterArr['grade3Phone']) {
                    $whereU[] = ['phone|uid|real_name','like','%'.$filterArr['grade3Phone'].'%'];
                    $user = \app\admin\model\HtnsUser::where($whereU)->find();
                    if($user){
                        $whereArr[] = ['grade3_uid', '=', $user['uid']];
                    }
                }
                if (isset($filterArr['grade4Phone']) && $filterArr['grade4Phone']) {
                    $whereU[] = ['phone|uid|real_name','like','%'.$filterArr['grade4Phone'].'%'];
                    $user = \app\admin\model\HtnsUser::where($whereU)->find();
                    if($user){
                        $whereArr[] = ['grade4_uid', '=', $user['uid']];
                    }
                }
                if (isset($filterArr['create_time']) && $filterArr['create_time']) {
                    $createTimeArr = explode(' - ',$filterArr['create_time']);
                    $whereArr[] = ['create_time', 'between', [strtotime($createTimeArr[0]) , strtotime($createTimeArr[1])]];
                }
            }
            if ($export) {
                $page  = 1;
                $limit = 10000;
            }
            $uid = input('uid');
            $whereArr[] = ['uid','=',$uid];

            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order('id desc')
                ->select()
                ->toArray();
            $userModel = new \app\admin\model\HtnsUser();
            foreach ($list as &$v) {
                $user = $userModel->find($v['uid']);
                if($user){
                    $v['real_name'] = $user['real_name'] ? $user['real_name'] : $user['nickname'];
                    $v['phone'] = $user['phone'];
                }
                $v['jmyc_grade'] = $userModel->getGradeName($user['jmyc_grade']);

            }
            // 导出
            if ($export) {
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('uid',$uid);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $activityId = 9;
        $this->assign('activityId', $activityId);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                // 默认值
                $product = HtnsProduct::find($post['product_id']);

                $post['image'] = $product['image'];
                $post['product_name'] = $product['store_name'];
//                $post['intro'] = $product['store_info'];
                $post['one_buy_limit_num'] = 9999;
                $post['all_buy_limit_num'] = 9999;
                // 折扣专区
                $post['cate_id'] = 0;
                $post['htns_activity_id'] = 9;
                $post['day_stock'] = 9999;
                $post['sum_stock'] = 9999;

                $post['start_time'] = time();
                $post['end_time'] = $post['start_time'] + 7 * 3600 * 24;//默认参与活动7天时间
                $save = $this->model->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $activityId = 8;
        $this->assign('activityId', $activityId);
        $row = $this->model->find($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $activityProductService = new ActivityProductService();

                $rev = $activityProductService->checkProductStock($post['product_id'],$post['stock']);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }
                $rev = $activityProductService->checkProductIsActivity($post['product_id'] , $id);
                if(!$rev['code']){
                    $this->error('保存失败1:'.$rev['msg']);
                }

                $save = $row->save($post);
            } catch (Exception $e) {
                $this->error('保存失败2:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败3');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    // 有效商品列表
    /**
     * @NodeAnotation(title="有效商品列表")
     */
    public function product_list()
    {
        $ret['code'] = 1;
        $ret['msg']  = '获取成功';
        $ret['data'] = [];

        $where[]     = ['is_show', '=', 1];
        $where[]     = ['is_del', '=', 0];
        $htnsProduct = HtnsProduct::where($where)->order('id desc')->select()->toArray();
        if ($htnsProduct) {
            foreach ($htnsProduct as $v) {
                $retv          = [
                    'id'         => $v['id'],
                    'store_name' => $v['store_name'],
                    'store_info' => $v['id'] . '-' . $v['store_name'],
                ];
                $ret['data'][] = $retv;
            }
        }
        return json($ret);
    }

}